#!/usr/bin/python

import sys, subprocess, re, os.path

#remove any superfluous slashes: //foo///bar//baz -> /foo/bar/baz 
# and replace ~ with home directory and ./ or relative path with
# absolute path
if len(sys.argv) > 1:
    filepath = os.path.abspath(re.sub("/{2,}", "/", sys.argv[-1]))

    wmctrl = subprocess.Popen(["wmctrl", "-l"], stdout=subprocess.PIPE)
    grep = subprocess.Popen(["grep", "GVIM"], stdin=wmctrl.stdout, stdout=subprocess.PIPE)
    wmctrl.stdout.close()
    gvimprocs = grep.stdout.readlines()
    grep.stdout.close()

    for gvimproc in gvimprocs:
        filename = gvimproc.split()[3]
        winname = gvimproc.split()[-1]
        path = re.sub(".+\((.+)\).+", "\g<1>", gvimproc).rstrip()
        if path:
            fullpath = re.sub("~", os.getenv("HOME"), os.path.join(path, filename))

            ## Now that we cleaned everthing up, we can compare
            if filepath == fullpath:
                cmd = ["wmctrl", "-a", winname]
                subprocess.call(cmd)
                sys.exit(0)
cmd = ["/usr/bin/gvim",]
cmd.extend(sys.argv[1:])
subprocess.call(cmd)
